﻿/* $RCSFile: CrmEntities.asmx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/Services/CrmEntities.asmx.cs $
 * $log$
 * Revision 20 2010/08/10 17:55:42  christian.surieux
 *   Missing comments in asax asmx ashx files
 * Revision 19 2010/08/09 09:44:01  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using CrmSdk;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;


namespace AddonNice.Services
{
    /// <summary>
    /// Acces to Crm entities for loading RadComboboxes
    /// </summary>
    [WebService(Namespace = "http://addonnice.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class CrmEntities : WebService
    {
        protected CRMWrapperBase Wrapper
        {
            get
            {
                return AddonNice.Security.PortalSecurity.Wrapper;
            }
        }

        protected void ResetWrapper(DynEntity dynEnt)
        {
            CRMWrapperBase  w   =   Wrapper;
            if ( !dynEnt.HasWrapper(w) )
                dynEnt.SetWrapper(w);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetSystemUsers(object context)
        {
            // We cannot use a dictionary as a parameter, because it is only supported by script services.
            // The context object should be cast to a dictionary at runtime.
            IDictionary<string, object> contextDictionary   =   (IDictionary<string, object>)context;
		    string filterString                             =   ((string)contextDictionary["FilterString"]).ToLower()+"%";
            List<CrmListItem> lst                           =   Wrapper.Util.QuerySystemUsers(filterString,100);
            RadComboBoxItemData[] result                    =   new RadComboBoxItemData[lst.Count];
		    for (int i=0 ; i < lst.Count ; i++)
		    {
                CrmListItem it                              =   lst[i];
			    RadComboBoxItemData itemData                =   new RadComboBoxItemData();
                itemData.Text                               =   it.name;
                itemData.Value                              =   it.ID.ToString();
			    result[i]                                   =   itemData;
		    }
		    return result;

        }
        [WebMethod]
        public RadComboBoxItemData[] GetAccounts(object context)
        {
            return GetEntity(context,CrmStr.account,CrmStr.accountid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetContacts(object context)
        {
            return GetEntity(context,CrmStr.contact,CrmStr.contactid,CrmStr.fullname);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetLeads(object context)
        {
            return GetEntity(context,CrmStr.lead,CrmStr.leadid,CrmStr.fullname);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetProducts(object context)
        {
            return GetEntity(context,CrmStr.product,CrmStr.productid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetOpportunities(object context)
        {
            return GetEntity(context,CrmStr.opportunity,CrmStr.opportunityid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetOrders(object context)
        {
            return GetEntity(context,CrmStr.salesorder,CrmStr.salesorderid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetQuotes(object context)
        {
            return GetEntity(context,CrmStr.quote,CrmStr.quoteid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetInvoices(object context)
        {
            return GetEntity(context,CrmStr.invoice,CrmStr.invoiceid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetDiscountTypes(object context)
        {
            return GetEntity(context,CrmStr.discounttype,CrmStr.discounttypeid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetSubjects(object context)
        {
            return GetEntity(context,CrmStr.subject,CrmStr.subjectid,CrmStr.title);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetKbArticles(object context)
        {
            return GetEntity(context,CrmStr.kbarticle,CrmStr.kbarticleid,CrmStr.title);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetContracts(object context)
        {
            return GetEntity(context,CrmStr.contract,CrmStr.contractid,CrmStr.title);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetPriceLevels(object context)
        {
            return GetEntity(context,CrmStr.pricelevel,CrmStr.pricelevelid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetTerritories(object context)
        {
            return GetEntity(context,CrmStr.territory,CrmStr.territoryid,CrmStr.name);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetCurrencies(object context)
        {
            return GetEntity(context,CrmStr.transactioncurrency,CrmStr.transactioncurrencyid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetUnits(object context)
        {
            return GetEntity(context,CrmStr.uom,CrmStr.uomid,CrmStr.name);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetUnitFamilies(object context)
        {
            return GetEntity(context,CrmStr.uomschedule,CrmStr.uomscheduleid,CrmStr.name);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetAnnotations(object context)
        {
            return GetEntity(context,CrmStr.annotation,CrmStr.annotationid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetBusinessUnits(object context)
        {
            return GetEntity(context,CrmStr.businessunit,CrmStr.businessunitid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetCampaigns(object context)
        {
            return GetEntity(context,CrmStr.campaign,CrmStr.campaignid,CrmStr.name);
        }

        public RadComboBoxItemData[] GetActivities(object context)
        {
            return GetEntity(context,CrmStr.activity,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetIncidents(object context)
        {
            return GetEntity(context,CrmStr.incident,CrmStr.incidentid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetLists(object context)
        {
            return GetEntity(context,CrmStr.list,CrmStr.listid,CrmStr.listname);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetTasks(object context)
        {
            return GetEntity(context,CrmStr.task,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetPhoneCalls(object context)
        {
            return GetEntity(context,CrmStr.phonecall,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetEMails(object context)
        {
            return GetEntity(context,CrmStr.email,CrmStr.activityid,CrmStr.subject);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetLetters(object context)
        {
            return GetEntity(context,CrmStr.letter,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetAppointments(object context)
        {
            return GetEntity(context,CrmStr.appointment,CrmStr.activityid,CrmStr.subject);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetFax(object context)
        {
            return GetEntity(context,CrmStr.fax,CrmStr.activityid,CrmStr.subject);
        }
        
        [WebMethod]
        public RadComboBoxItemData[] GetCampaignActivities(object context)
        {
            return GetEntity(context,CrmStr.campaignactivity,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetCampaignResponses(object context)
        {
            return GetEntity(context,CrmStr.campaignresponse,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetServiceAppointments(object context)
        {
            return GetEntity(context,CrmStr.serviceappointment,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetQueues(object context)
        {
            return GetEntity(context,CrmStr.queue,CrmStr.queueid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetSavedQueries(object context)
        {
            return GetEntity(context,CrmStr.savedquery,CrmStr.savedqueryid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetUserQueries(object context)
        {
            return GetEntity(context,CrmStr.userquery,CrmStr.userqueryid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxItemData[] GetAccountMailTemplates(object context)
        {
            // We cannot use a dictionary as a parameter, because it is only supported by script services.
            // The context object should be cast to a dictionary at runtime.
            IDictionary<string, object> contextDictionary   =   (IDictionary<string, object>)context;
		    string filterString                             =   ((string)contextDictionary["FilterString"]).ToLower()+"%";
            SortedList<Guid,ADNDynTemplate> lst             =   ADNDynTemplate.ReadAll(Wrapper,ResetWrapper,CrmStr.account,-1,true);
            RadComboBoxItemData[] result                    =   new RadComboBoxItemData[lst.Count];
		    for (int i=0 ; i < lst.Count ; i++)
		    {
                ADNDynTemplate dynT                         =   lst.Values[i];
			    RadComboBoxItemData itemData                =   new RadComboBoxItemData();
                itemData.Text                               =   dynT.title;
                itemData.Value                              =   dynT.templateid.ToString();
			    result[i]                                   =   itemData;
		    }
		    return result;
        }

        [WebMethod]
        public RadComboBoxItemData[] GetContactMailTemplates(object context)
        {
            // We cannot use a dictionary as a parameter, because it is only supported by script services.
            // The context object should be cast to a dictionary at runtime.
            IDictionary<string, object> contextDictionary   =   (IDictionary<string, object>)context;
		    string filterString                             =   ((string)contextDictionary["FilterString"]).ToLower()+"%";
            SortedList<Guid,ADNDynTemplate> lst             =   ADNDynTemplate.ReadAll(Wrapper,ResetWrapper,CrmStr.contact,-1,true);
            RadComboBoxItemData[] result                    =   new RadComboBoxItemData[lst.Count];
		    for (int i=0 ; i < lst.Count ; i++)
		    {
                ADNDynTemplate dynT                         =   lst.Values[i];
			    RadComboBoxItemData itemData                =   new RadComboBoxItemData();
                itemData.Text                               =   dynT.title;
                itemData.Value                              =   dynT.templateid.ToString();
			    result[i]                                   =   itemData;
		    }
		    return result;
        }

        [WebMethod]
        public RadComboBoxItemData[] GetLeadMailTemplates(object context)
        {
            // We cannot use a dictionary as a parameter, because it is only supported by script services.
            // The context object should be cast to a dictionary at runtime.
            IDictionary<string, object> contextDictionary   =   (IDictionary<string, object>)context;
		    string filterString                             =   ((string)contextDictionary["FilterString"]).ToLower()+"%";
            SortedList<Guid,ADNDynTemplate> lst             =   ADNDynTemplate.ReadAll(Wrapper,ResetWrapper,CrmStr.lead,-1,true);
            RadComboBoxItemData[] result                    =   new RadComboBoxItemData[lst.Count];
		    for (int i=0 ; i < lst.Count ; i++)
		    {
                ADNDynTemplate dynT                         =   lst.Values[i];
			    RadComboBoxItemData itemData                =   new RadComboBoxItemData();
                itemData.Text                               =   dynT.title;
                itemData.Value                              =   dynT.templateid.ToString();
			    result[i]                                   =   itemData;
		    }
		    return result;
        }

        [WebMethod]
        public RadComboBoxItemData[] GetOrderMailTemplates(object context)
        {
            // We cannot use a dictionary as a parameter, because it is only supported by script services.
            // The context object should be cast to a dictionary at runtime.
            IDictionary<string, object> contextDictionary   =   (IDictionary<string, object>)context;
		    string filterString                             =   ((string)contextDictionary["FilterString"]).ToLower()+"%";
            SortedList<Guid,ADNDynTemplate> lst             =   ADNDynTemplate.ReadAll(Wrapper,ResetWrapper,CrmStr.salesorder,-1,true);
            RadComboBoxItemData[] result                    =   new RadComboBoxItemData[lst.Count];
		    for (int i=0 ; i < lst.Count ; i++)
		    {
                ADNDynTemplate dynT                         =   lst.Values[i];
			    RadComboBoxItemData itemData                =   new RadComboBoxItemData();
                itemData.Text                               =   dynT.title;
                itemData.Value                              =   dynT.templateid.ToString();
			    result[i]                                   =   itemData;
		    }
		    return result;
        }

        [WebMethod]
        public RadComboBoxItemData[] GetEntity(object context,string entName,string primaryKey,string displayKey)
        {
            // We cannot use a dictionary as a parameter, because it is only supported by script services.
            // The context object should be cast to a dictionary at runtime.
            IDictionary<string, object> contextDictionary   =   (IDictionary<string, object>)context;
		    string filterString                             =   ((string)contextDictionary["FilterString"]).ToLower()+"%";
            List<CrmListItem> lst                           =   Wrapper.Util.EntitiesLike(entName,primaryKey,displayKey,filterString,100,true);
            RadComboBoxItemData[] result                    =   new RadComboBoxItemData[lst.Count];
		    for (int i=0 ; i < lst.Count ; i++)
		    {
                CrmListItem it                              =   lst[i];
			    RadComboBoxItemData itemData                =   new RadComboBoxItemData();
                itemData.Text                               =   it.name;
                itemData.Value                              =   it.ID.ToString();
			    result[i]                                   =   itemData;
		    }
		    return result;
        }

        [WebMethod]
        public RadComboBoxData GetAccountsPaged(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.account,CrmStr.accountid,CrmStr.name);
        }
        
        [WebMethod]
        public RadComboBoxData GetContacsPaged(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.contact,CrmStr.contactid,CrmStr.fullname);
        }
        
        [WebMethod]
        public RadComboBoxData GetLeadsPaged(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.lead,CrmStr.leadid,CrmStr.fullname);
        }

        [WebMethod]
        public RadComboBoxData GetProductsPaged(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.product,CrmStr.productid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxData GetOpportunitiesPaged(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.opportunity,CrmStr.opportunityid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxData GetOrdersPaged(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.salesorder,CrmStr.salesorderid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxData GetActivitiesPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.activity,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetIncidentsPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.incident,CrmStr.incidentid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetTasksPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.task,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetPhoneCallsPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.phonecall,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetEMailsPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.email,CrmStr.activityid,CrmStr.subject);
        }
        
        [WebMethod]
        public RadComboBoxData GetLettersPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.letter,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetAppointmentsPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.appointment,CrmStr.activityid,CrmStr.subject);
        }
        
        [WebMethod]
        public RadComboBoxData GetFaxPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.fax,CrmStr.activityid,CrmStr.subject);
        }
        
        [WebMethod]
        public RadComboBoxData GetCampaignActivities(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.campaignactivity,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetCampaignResponsesPages(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.campaignresponse,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetServiceAppointments(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.serviceappointment,CrmStr.activityid,CrmStr.subject);
        }

        [WebMethod]
        public RadComboBoxData GetSavedQueries(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.savedquery,CrmStr.savedqueryid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxData GetUserQueries(RadComboBoxContext context)
        {
            return GetEntityPaged(context,CrmStr.userquery,CrmStr.userqueryid,CrmStr.name);
        }

        [WebMethod]
        public RadComboBoxData GetEntityPaged(RadComboBoxContext context,string entName,string primaryKey,string displayKey)
        {
            string filterString                     =   context.Text +"%";
            List<CrmListItem> lst                   =   Wrapper.Util.EntitiesLike(entName,primaryKey,displayKey,filterString,100,true);
	        List<RadComboBoxItemData> result        =   new List<RadComboBoxItemData>(context.NumberOfItems);
	        RadComboBoxData comboData               =   new RadComboBoxData();
	        try
	        {
		        int itemsPerRequest                 =   10;
		        int itemOffset                      =   context.NumberOfItems;
		        int endOffset                       =   itemOffset + itemsPerRequest;
		        if (endOffset > lst.Count)
		        {
			        endOffset = lst.Count;
		        }
		        if (endOffset == lst.Count)
		        {
			        comboData.EndOfItems            =   true;
		        }
		        else
		        {
			        comboData.EndOfItems            =   false;
		        }
		        result                              =   new List<RadComboBoxItemData>(endOffset - itemOffset);
		        for (int i = itemOffset; i < endOffset; i++)
		        {
			        RadComboBoxItemData itemData = new RadComboBoxItemData();
                    CrmListItem it                      =   lst[i];
                    itemData.Text                       =   it.name;
                    itemData.Value                      =   it.ID.ToString();
			        result.Add(itemData);
			        }

		        if (lst.Count > 0)
		        {
			        comboData.Message = String.Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", endOffset.ToString(), lst.Count.ToString());
		        }
		        else
		        {
			        comboData.Message = "No matches";
		        }
	        }
	        catch(Exception e)
	        {
		        comboData.Message = e.Message;
	        }

	        comboData.Items = result.ToArray();
	        return comboData;
            }
        }
}
